﻿using static CyberU;
using static CyberU.UI;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using System.Reflection; // 提供 MemberInfo 类型
using Newtonsoft.Json.Serialization; // 提供 DefaultContractResolver 类型
using System.Collections.Generic;
using System.Linq;

public partial class CyberU
{
    // region Json
    public static T FromJson<T>(string filePath)
    {
        return ReadJson<T>(filePath);
    }

    public static T ReadJson<T>(string filePath)
    {
        if (!File.Exists(filePath))
        {
            Debug.LogError($"文件不存在: {filePath}");
            return default(T);
        }

        string json = File.ReadAllText(filePath);
        T obj = JsonConvert.DeserializeObject<T>(json);
        return obj;
    }

    public static JObject ReadJson(string filePath)
    {
        if (!File.Exists(filePath))
        {
            Debug.LogError($"文件不存在: {filePath}");
            return null;
        }

        try
        {
            string json = File.ReadAllText(filePath);
            JObject jObject = JObject.Parse(json);
            return jObject;
        }
        catch (Exception e)
        {
            Debug.LogError($"读取或解析 JSON 出错: {e.Message}");
            return null;
        }
    }

    public class IgnoreLinearPropertyResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
        {
            var properties = base.CreateProperties(type, memberSerialization);

            // 过滤掉所有名为 "linear" 的属性
            return properties.Where(p => p.PropertyName != "linear").ToList();
        }
    }

    public static void WriteJson(string filePath, object obj)
    {
        try
        {
            string directoryPath = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            string json = Object2Json(obj);
            File.WriteAllText(filePath, json);
            // Debug.Log($"Successfully wrote JSON to: {filePath}");
        }
        catch (Exception e)
        {
            Debug.LogError($"JSON write error: {e.Message}\n{e.StackTrace}");
        }
    }

    public static string Object2Json(object obj)
    {
        var settings = new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
            ContractResolver = new DebugContractResolver(),
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        };
        string json = JsonConvert.SerializeObject(obj, settings);
        return json;
    }

    public class DebugContractResolver : DefaultContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty property = base.CreateProperty(member, memberSerialization);
            // Debug.Log($"Serializing Property: {member.DeclaringType?.Name}.{member.Name} (Type: {property.PropertyType.Name})");
            if (typeof(Component).IsAssignableFrom(property.PropertyType) ||
                typeof(GameObject).IsAssignableFrom(property.PropertyType))
            {
                Debug.LogWarning($"Skipping Unity component: {member.DeclaringType?.Name}.{member.Name}");
                property.Ignored = true;
            }
            return property;
        }
    }

    public static T DeserializeJObject<T>(JObject jObject)
    {
        return jObject.ToObject<T>();
    }

    public static JObject SerializeToJObject(object obj)
    {
        return JObject.FromObject(obj);
    }
    //endregion
}